<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-button type="primary" @click="addDialogVisible = true"
        >添加角色</el-button
      >
      <el-table :data="list" border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bb', 'vcenter', index1 === 0 ? 'bt' : '']"
              :key="level1.id"
              v-for="(level1, index1) in scope.row.children"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  effect="plain"
                  size="mini"
                  @close="remove(scope.row, level1.id)"
                  >{{ level1.authName }}</el-tag
                >
                <i class="el-icon-arrow-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[index2 === 0 ? '' : 'bt']"
                  :key="level2.id"
                  v-for="(level2, index2) in level1.children"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      effect="plain"
                      size="mini"
                      @close="remove(scope.row, level2.id)"
                      >{{ level2.authName }}</el-tag
                    >
                    <i class="el-icon-arrow-right"></i>
                  </el-col>
                  <!-- 渲三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      effect="plain"
                      size="mini"
                      :key="level3.id"
                      v-for="level3 in level2.children"
                      @close="remove(scope.row, level3.id)"
                      >{{ level3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="getThisList(scope)">编辑</el-button>
            <el-button type="text" @click="delThisList(scope)">删除</el-button>
            <el-button type="text" @click="setRight(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色dialog -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="clearForm"
    >
      <el-form
        :model="addUserForm"
        ref="addUserRef"
        :rules="addUserRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addUserForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addUserForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUserLists">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色dialog -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="clearEditForm"
    >
      <el-form :model="editUserForm" ref="editUserRef" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="editUserForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editUserForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUserLists">确 定</el-button>
        <el-button @click="editDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限dialog -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightShow"
      width="50%"
      @close="clearTree"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsLists"
        :props="treeProps"
        node-key="id"
        :default-checked-keys="defKeys"
        default-expand-all
        show-checkbox
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightShow = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addUserForm: {
        roleName: "",
        roleDesc: "",
      },
      editUserForm: {
        roleName: "",
        roleDesc: "",
        id: "",
      },
      addUserRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 5, max: 10, message: "长度在5到10个字符", trigger: "blur" },
        ],
      },
      setRightShow: false,
      rightsLists: [],
      // 树形控件的属性绑定对象
      treeProps: {
        children: "children",
        label: "authName",
      },
      // 默认选中的节点ID值
      defKeys: [],
      roleId: "",
    };
  },
  methods: {
    async getUserLists() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败");
      }
      this.list = res.data;
    },
    // 添加角色
    addUserLists() {
      this.$refs.addUserRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.addUserForm);
        if (res.meta.status !== 201) {
          return this.$message.error("创建失败");
        }
        this.getUserLists();
        this.$message.success("创建成功");
        this.addDialogVisible = false;
      });
    },
    // 编辑角色
    async editUserLists() {
      const { data: res } = await this.$http.put(
        "roles/" + this.editUserForm.id,
        this.editUserForm
      );
      if (res.meta.status !== 200) {
        return this.$message.error("编辑失败");
      }
      this.getUserLists();
      this.$message.success("编辑成功");
      this.editDialogVisible = false;
    },
    // 删除角色
    async delThisList(message) {
      const { data: res } = await this.$http.delete("roles/" + message.row.id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getUserLists();
    },
    // 关闭dialog时清空内容
    clearForm() {
      this.$refs.addUserRef.resetFields();
    },
    clearEditForm() {
      this.$refs.editUserRef.resetFields();
    },
    // 获取此列数据
    getThisList(msg) {
      this.editDialogVisible = true;
      this.editUserForm = msg.row;
    },
    // 删除权限
    remove(role, rightId) {
      this.$confirm("是否删除此权限？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error("取消权限失败");
          }
          this.$message.success("取消权限成功!");
          role.children = res.data;
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 分配权限
    async setRight(role) {
      this.roleId = role.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限数据失败");
      }
      this.rightsLists = res.data;
      // 获取第三级节点的id
      this.getThirdNode(role, this.defKeys);

      this.setRightShow = true;
    },
    // 利用递归获取权限中的第三级节点的数据
    getThirdNode(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach((item) => {
        this.getThirdNode(item, arr);
      });
    },
    clearTree() {
      this.defKeys = [];
    },
    // 保存所选权限
    async save() {
      const key = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = key.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功!");
      this.getUserLists();
      this.setRightShow = false;
    },
  },
  created() {
    this.getUserLists();
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bt {
  border-top: 1px solid #eee;
}
.bb {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>